package com.party.wechat;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.party.dto.ImageDto;
import com.party.dto.Response;
import com.party.tool.UploadUtils;

/**
 * 
 * @author Caizhf
 * @date 2017年8月18日上午2:03:59
 * @version v.0.1
 * @email 1115054416@qq.com 
 *
 * <p>Description: 微信二维码图片增加与更新操作</p>
 *
 */
@RestController
@RequestMapping("/wechat")
public class ImageController {
	@Autowired
	private WechatImageMapper mapper;
	
	private static final Logger logger = LoggerFactory.getLogger(ImageController.class);
	
	@Value("${image.path}")
	private String imagePath;
	
	@Value("${image.tomcat.uri}")
	private String imageUri;
	
	
	/**
	 * 本接口有直接上传，覆盖上传的功能
	 * 
	 * @param image		所传图片
	 * @param wechatNum	微信公众号码（可选传入）
	 * @param req		request对象（Spring自动传入）
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/save")
	@Transactional
	public Response save(@RequestParam("image")MultipartFile image,String wechatNum,HttpServletRequest req) throws Exception{
		if(image.isEmpty())
			return Response.success("图片不能为空");
		WeChatImg img = mapper.find();
		//如果数据库中有记录了，先删除记录，再存入
		if(null!=img)
			mapper.deleteAll();
		//上传并存储入服务器
		ImageDto imd = UploadUtils.MvcUpload(image, imagePath);
		//数据库存储文件名操作
		mapper.save(new WeChatImg(wechatNum,imd.getImageName()));
		return Response.success();
	}
	
	//显示图片
	@RequestMapping("/get")
	public Response get(HttpServletRequest req){
		WeChatImg img = mapper.find();
		String reqUrl = req.getRequestURL().toString();
		String reqUri = req.getRequestURI();
		String showUrl = reqUrl.replaceAll(reqUri, imageUri+img.getImgName());
		return Response.success(showUrl);
	}
	
}
